package com.xbdun.service.bmp.service.system.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbdun.common.api.Client;
import com.xbdun.common.enums.YesOrNoEnum;
import com.xbdun.common.page.Pager;
import com.xbdun.dao.bmp.entity.XbdunOrleDepartDo;
import com.xbdun.dao.bmp.mapper.PowerRoleDepartMapper;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.OrleDepartPagerRequest;
import com.xbdun.facade.bmp.request.system.OrleDepartRequest;
import com.xbdun.facade.bmp.response.system.OrleDepartPagerResponse;
import com.xbdun.service.bmp.biz.OrleDepartBiz;
import com.xbdun.service.bmp.service.system.OrleDepartService;

@Service
public class OrleDepartServiceImpl implements OrleDepartService {
	@Autowired
	OrleDepartBiz orleDepartBiz;
	
	@Autowired
	PowerRoleDepartMapper powerRoleDepartMapper;
	
	@Transactional
	public void addDepartRoles(OrleDepartRequest request, Client client) throws Exception {

		XbdunOrleDepartDo xbdunOrleDepartDo = new XbdunOrleDepartDo();
		
		xbdunOrleDepartDo.setBlSpecial(request.getBlspacialRole()?YesOrNoEnum.YES.getKey():YesOrNoEnum.No.getKey());
		xbdunOrleDepartDo.setCode(request.getDepartCode());//部门Code
		xbdunOrleDepartDo.setOrgCode(client.getOrgCode());//机构Code
		xbdunOrleDepartDo.setOptionUser(client.getUserName());//操作人
		
		orleDepartBiz.addOrleDeparts(xbdunOrleDepartDo,request.getRoleId());
	}
	
	public Pager<OrleDepartPagerResponse> queryOrleDepartOrg(OrleDepartPagerRequest request, Client client) {
		return orleDepartBiz.queryPager(client.getOrgCode(),request);
	}
	
	@Transactional
	public void delDepartRole(Long id, Client client) {
		XbdunOrleDepartDo xbdunOrleDepartById = orleDepartBiz.getXbdunOrleDepartById(id,client.getOrgCode());
		if(null == xbdunOrleDepartById){
			throw BmpBizException.DB_SELECTONE_IS_NULL.newInstance("选择当前的数据不存在");
		}
		//查询当前机构下的id是否还存在子项
		if(powerRoleDepartMapper.existItem(id,client.getOrgCode())>0){
			throw BmpBizException.ITEMS_EXIST.newInstance("当前角色存在关联用户，请【设置权限】取消所有权限进行操作");
		}
		if(0==orleDepartBiz.delXbdunOrleDepartById(id,client.getOrgCode(),xbdunOrleDepartById.getVersion())){
			throw BmpBizException.DB_UPDATE_RESULT_0.newInstance("数据删除失败");
		}
	}
}